<template>
	<view class="container">

		<view class="">
			<u-subsection fontSize="14px" :list="list" :current="curNow" @change="sectionChange" bgColor="#3c9cff">
			</u-subsection>
		</view>

		<view>
			<u--form labelPosition="top" :model="userInfo" :rules="rules" ref="uForm">
				<u-form-item label="业务开发" prop="businessDevelop" borderBottom labelWidth="200px">
					<u--input v-model="userInfo.businessDevelop" border="none"></u--input>
				</u-form-item>

				<u-form-item label="老板姓名" prop="nickName" borderBottom labelWidth="200px">
					<u--input v-model="userInfo.nickName" border="none"></u--input>
				</u-form-item>


				<u-form-item label="老板手机号" prop="userName" borderBottom labelWidth="200px">
					<u--input v-model="userInfo.userName" border="none"></u--input>
				</u-form-item>


				<u-form-item label="商户名称" prop="merchantName" borderBottom labelWidth="200px">
					<u--input v-model="userInfo.merchantName" border="none"></u--input>
				</u-form-item>

				<u-form-item label="商户地址" prop="addressFull" borderBottom labelWidth="200px">
					<u--input v-model="userInfo.addressFull" border="none"></u--input>
				</u-form-item>

				<u-form-item label="开始时间" prop="params.beginTime" borderBottom labelWidth="200px"
					@click="openDatetimePicker">
					<u--input v-model="userInfo.params.beginTime" border="none"></u--input>
				</u-form-item>

				<u-form-item label="结束时间" prop="params.endTime" borderBottom labelWidth="200px"
					@click="openDatetimePicker2">
					<u--input v-model="userInfo.params.endTime" border="none"></u--input>
				</u-form-item>

				<buuug7-simple-datetime-picker ref="myPicker" @submit="createTimeStart" :start-year="2023"
					:end-year="2099" :time-init="1688860800000" :time-hide="[true, true, true, false, false, false]"
					:time-label="['年', '月', '日', '时', '分', '秒']" />

				<buuug7-simple-datetime-picker ref="myPicker2" @submit="createTimeEnd" :start-year="2023"
					:end-year="2099" :time-init="1688860800000" :time-hide="[true, true, true, false, false, false]"
					:time-label="['年', '月', '日', '时', '分', '秒']" />

				<u-button type="primary" @click="getPageList(1)">查询</u-button>
			</u--form>
		</view>

		<view v-if="merchantLists.length > 0">
			<u-list @scrolltolower="scrolltolower" class="u-list">
				<u-list-item v-for="(item, index) in merchantLists" :key="index">
					<view class="box">
						<u--form labelPosition="left" :model="item" >
							<u-form-item label="userId"  borderBottom labelWidth="120px">
								<u--input v-model="item.userId" border="none" disabled></u--input>
							</u-form-item>
							<u-form-item label="业务开发"  borderBottom labelWidth="120px">
								<u--input v-model="item.businessDevelop" border="none" disabled></u--input>
							</u-form-item>
							<u-form-item label="老板姓名"  borderBottom labelWidth="120px">
								<u--input v-model="item.nickName" border="none" disabled></u--input>
							</u-form-item>

							<u-form-item label="老板手机号"  borderBottom labelWidth="120px">
								<u--input v-model="item.userName" border="none"></u--input>
							</u-form-item>

							<u-form-item label="商户名称" borderBottom labelWidth="120px">
								<u--input v-model="item.merchantName" border="none" ></u--input>
							</u-form-item>
							
							
							<u-form-item label="设备数量"  borderBottom labelWidth="120px">
								<u--input v-model="item.deviceCount" border="none" disabled></u--input>
							</u-form-item>
							
							<u-form-item label="商户分润"  borderBottom labelWidth="120px">
								<u--input v-model="userInfo.shareBenefit" border="none" disabled></u--input>
							</u-form-item>

							<u-form-item label="商户地址"  borderBottom labelWidth="120px">
								<u--input v-model="item.addressFull" border="none"></u--input>
							</u-form-item>




							<u-form-item label="地址来源" borderBottom labelWidth="120px">
								<u-radio-group v-model="item.addressSource" placement="row">
									<u-radio :customStyle="{margin: '8px'}"
										v-for="(item2, index2) in addressSourceRadioValue" :key="index2"
										:label="item2.name" :name="item2.name" @change="addressSourceChange(index2)">
									</u-radio>
								</u-radio-group>
							</u-form-item>




							<u-form-item label="创建时间"  borderBottom labelWidth="120px">
								<u--input v-model="item.createTime" border="none" disabled></u--input>
							</u-form-item>


							<view class="updateMessage" v-if="checkRole(['admin'])">
								<view class="mybuttom">
									<u-button type="primary" size="mini" @click="myUptate(item)">修改</u-button>
								</view>
								<view class="mybuttom">
									<u-button type="error" size="mini" @click="myDelete(item)">删除</u-button>
								</view>
								<view class="mybuttom">
									<u-button type="error" size="mini" @click="updateSetMeal(item)">修改套餐</u-button>
								</view>
							</view>
						</u--form>
					</view>
				</u-list-item>
			</u-list>

			<view style="display: flex; justify-content: center; margin-bottom: 20px; margin-top: 10px;">
				<view v-if="userInfo.pageTotal > userInfo.pageNum ">
					下拉加载更多...
				</view>
				<view class="" v-else>没有更多数据..</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		validateDate
	} from '@/utils/common';
	import {
		checkPermi,
		checkRole
	} from "@/utils/permission"; // 权限判断函数
	import {
		getUserPageList,
		updateUser,
		deleteUserByIds
	} from "@/api/system/user.js"
	export default {

		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},

		data() {
			return {
				list: ['添加商户', '查找商户'],
				curNow: 1,
				merchantLists: [],
				userInfo: {
					shareBenefit: '98%',
					businessDevelop: '',
					userName: '',
					nickName: "",
					merchantName: "",
					addressPrefix: '',
					addressInfo: '',
					addressFull: '',
					directTrain: '0',
					addressSource: '0',
					userType: 33,
					createTimeStart: '',
					createTimeEnd: '',

					pageNum: 1,
					pageSize: 5,
					params: {
						"beginTime": '',
						'endTime': ''
					},
					pageTotal: 1,
				},
				directTrainRadioValue: [{
					name: '正常过审',
					disabled: true
				}, {
					name: '直通车',
					disabled: false
				}],

				addressSourceRadioValue: [{
					name: '美团',
					disabled: true
				}, {
					name: '携程',
					disabled: false
				}, {
					name: '飞猪',
					disabled: false
				}],

			}
		},
		methods: {

			checkPermi,
			checkRole,
			addressSourceChange(n) {
				console.log('addressSourceChange', n);
				this.userInfo.addressSource = n;
			},
			//整个页面底部
			onReachBottom() {
				console.log('到达底部333')
			},
			//整个页面底部
			onReachBottom() {
				console.log('到达底部333')
			},
			//只是list这个区域的到达底部
			scrolltolower() {
				console.log('到底部了翻页')
				if (this.userInfo.pageNum >= this.userInfo.pageTotal) {
					uni.$u.toast('没有更多数据!');
				} else {
					this.userInfo.pageNum = this.userInfo.pageNum + 1;
					this.getUserPageList(2);
				}
			},
			sectionChange(index) {
				let oldCurNow = this.curNow;
				this.curNow = index;
				if (index === 0 && oldCurNow === 1) {
					uni.redirectTo({
						url: '/pages/merchant/merchant'
					})
				}
			},

			rules: {
				'nickName': [{
					type: 'string',
					required: false,
					max: 8,
					message: '老板姓名',
					trigger: ['blur', 'change']
				}],
				'userName': [{
					type: 'number',
					required: false,
					message: '请输入11位手机号',
					trigger: ['blur', 'change']
				}],
				'createTimeStart': [{
					type: 'string',
					required: false,

					message: '点击选择时间',
					trigger: ['blur', 'change']
				}],

				'createTimeEnd': [{
					type: 'string',
					required: false,
					message: '点击选择时间',
					trigger: ['blur', 'change']
				}],
			},

			// 打开picker
			openDatetimePicker() {
				this.$refs.myPicker.show();
			},

			// 关闭picker
			closeDatetimePicker() {
				this.$refs.myPicker.hide();
			},

			openDatetimePicker2() {
				this.$refs.myPicker2.show();
			},

			// 关闭picker
			closeDatetimePicker2() {
				this.$refs.myPicker2.hide();
			},

			createTimeStart(e) {
				console.log(e);
				// {year: "2023", month: "07", day: "11", hour: "15", minute: "21", seconds: '55'}
				this.userInfo.params.beginTime = `${e.year}-${e.month}-${e.day}`;
			},
			createTimeEnd(e) {
				console.log(e);
				// {year: "2023", month: "07", day: "11", hour: "15", minute: "21", seconds: '55'}
				this.userInfo.params.endTime = `${e.year}-${e.month}-${e.day}`;
			},
			resetUserInfo() {
				this.merchantLists = [];
				this.userInfo.pageNum = 1,
					this.userInfo.pageSize = 5,
					this.userInfo.pageTotal = 1
			},
			async getPageList(tag) {
				try {
					if (tag === 1) {
						this.resetUserInfo();
					}
					const res = await this.dateValidate();
					console.log('res' + res);
					console.log('res' + typeof res);
					if (!res) {
						console.log('数据校验失败return')
						return;
					}

					const res2 = await getUserPageList(this.userInfo);
					console.log(JSON.stringify(res2));

					res2.rows.forEach(item => {
						// 假设后端返回的索引为 item.addressSourceIndex
						const index = item.addressSource;
						// 确保索引有效
						if (index >= 0 && index < this.addressSourceRadioValue.length) {
							item.addressSource = this.addressSourceRadioValue[index].name; // 设置为对应的中文标签
						}
					});
					this.merchantLists.push(...res2.rows);

					this.userInfo.pageTotal = Math.ceil(res2.total / this.userInfo.pageSize);

				} catch (error) {
					console.error('发生错误:', error);
				}
			},
			myUptate(itme) {
				console.log(JSON.stringify(itme))
				// 找到中文对应的下标
				const selectedIndex = this.addressSourceRadioValue.findIndex(
					k => k.name === itme.addressSource
				);

				itme.addressSource = selectedIndex;
				console.log(JSON.stringify(itme))
				updateUser(itme).then(response => {
					this.$modal.msgSuccess("修改成功");
					this.getPageList(1);
				});
			},

			myDelete(itme) {
				console.log(JSON.stringify(itme))
				this.$modal.confirm('是否确认删除用户编号为"' + itme.userId + '"的数据项？').then(function() {
					return deleteUserByIds(itme.userId);
				}).then(() => {
					this.getPageList(1);
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {
					this.$modal.msgError('删除失败')
				});
			},

			updateSetMeal(itme) {
				uni.navigateTo({
					url: '../setMeal/setMealSearch?userId='+itme.userId
				})
			},

			dateValidate() {
				return new Promise((resolve, reject) => {
					let tag = true;
					this.$refs.uForm.validate().then(res => {
						if (this.userInfo.params.beginTime != '' && this.userInfo.params
							.beginTime !=
							null && this.userInfo.params.beginTime != undefined) {
							if (!validateDate(this.userInfo.params.beginTime)) {
								tag = false;
								uni.$u.toast('开始日期格式不对');
							}
						}
						if (this.userInfo.params.endTime != '' && this.userInfo.params
							.endTime != null &&
							this.userInfo.params.endTime != undefined) {
							if (!validateDate(this.userInfo.params.endTime)) {
								uni.$u.toast('结束日期格式不对');
								tag = false;
							}
							if (this.userInfo.params.beginTime == '') {
								uni.$u.toast('开始日期也必须选择');
								tag = false;
							}
						}
						if (tag) {
							resolve(true);
						} else {
							resolve(false);
						}
					}).catch(errors => {
						console.log('Validation errors:' + errors);
						uni.$u.toast('校验失败11111111' + JSON.stringify(errors));
						resolve(false); // 这里也返回 false
					});
				});
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		//width: 94%;
		padding: 12px;
		display: flex;
		flex-direction: column;
		margin: auto;
		background: linear-gradient(180deg, #f0f0f0 0%, #d0eaff 100%);
		height: 100vh;
	}

	.updateMessage {
		display: flex;
		justify-content: right;
		height: 40px;
		align-items: center;

		.mybuttom {
			margin-right: 10px;
		}

	}


	.box {
		background-color: #ffffff;
		/* 背景颜色 */
		border-radius: 8px;
		/* 圆角 */
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		/* 阴影效果 */
		padding: 4px;
		/* 内边距 */
		margin-top: 8px;
		/* 外边距 */
		transition: box-shadow 0.3s;
		/* 动画效果 */
	}

	.box:hover {
		box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
		/* 增强阴影 */
	}

	.u-list {
		max-height: 400px;
		/* 设置最大高度 */
		overflow-y: auto;
		/* 允许垂直滚动 */
	}
</style>